package com.tydic.portal.service.impl;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import com.tydic.borderer.domain.BordererInfo;
import com.tydic.borderer.service.IBordererInfoService;
import com.tydic.common.core.constant.Constants;
import com.tydic.common.core.constant.GlobalConstants;
import com.tydic.common.core.domain.model.LoginUser;
import com.tydic.common.core.enums.LoginType;
import com.tydic.common.core.exception.user.UserException;
import com.tydic.common.core.utils.MessageUtils;
import com.tydic.common.core.utils.ServletUtils;
import com.tydic.common.core.utils.SpringUtils;
import com.tydic.common.log.event.LogininforEvent;
import com.tydic.common.mybatis.helper.DataPermissionHelper;
import com.tydic.common.redis.utils.RedisUtils;
import com.tydic.common.satoken.utils.LoginHelper;
import com.tydic.enterprise.domain.Enterprise;
import com.tydic.enterprise.service.IEnterpriseService;
import com.tydic.portal.service.PortalLoginService;
import com.tydic.system.domain.SysUser;
import com.tydic.system.domain.vo.SysUserVo;
import com.tydic.system.mapper.SysUserMapper;
import com.tydic.system.service.ISysPermissionService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.function.Supplier;

@Slf4j
@RequiredArgsConstructor
@Service
public class PortalLoginServiceImpl implements PortalLoginService {
    private final SysUserMapper sysUserMapper;
    private final ISysPermissionService sysPermissionService;
    private final IBordererInfoService bordererInfoService;
    private final IEnterpriseService enterpriseService;
    @Value("${user.password.maxRetryCount}")
    private Integer maxRetryCount;
    @Value("${user.password.lockTime}")
    private Integer lockTime;

    @Override
    public void logout() {
        try {
            LoginUser loginUser = LoginHelper.getLoginUser();
            if (ObjectUtil.isNull(loginUser)) {
                return;
            }
            recordLoginInfo(loginUser.getLoginCode(), Constants.LOGOUT, MessageUtils.message("user.logout.success"));
        } catch (NotLoginException ignored) {
        } finally {
            try {
                StpUtil.logout();
            } catch (NotLoginException ignored) {
            }
        }
    }


    @Override
    public void recordLoginInfo(String loginCode, String status, String message) {
        LogininforEvent logininforEvent = new LogininforEvent();
        logininforEvent.setUsername(loginCode);
        logininforEvent.setStatus(status);
        logininforEvent.setMessage(message);
        logininforEvent.setRequest(ServletUtils.getRequest());
        SpringUtils.context().publishEvent(logininforEvent);
    }


    @Override
    public LoginUser buildLoginUser(SysUserVo user) {
        LoginUser loginUser = BeanUtil.toBean(user, LoginUser.class);
        if (CharSequenceUtil.isBlank(loginUser.getMobile())) {
            loginUser.setMobile(user.getLoginCode());
        }
        loginUser.setToken(IdUtil.getSnowflakeNextIdStr());
        if (loginUser.isBordererAgent() || loginUser.isBorderer()) {
            BordererInfo bordererInfo = bordererInfoService.getBordererInfoByUserCode(loginUser.getUserCode());
            if (bordererInfo != null) {
                loginUser.setBorderInfoId(bordererInfo.getId());
            }
        } else if (loginUser.isEnterpriseAdmin()) {
            Enterprise enterprise = enterpriseService.getEnterpriseByUserCode(loginUser.getUserCode());
            if (enterprise != null) {
                loginUser.setEnterpriseId(enterprise.getId());
            }
        }
        return loginUser;
    }

    @Override
    public void recordLoginInfo(String userId, String ip) {
        SysUser sysUser = new SysUser();
//        sysUser.setUserId(userId);
//        sysUser.setLoginIp(ip);
//        sysUser.setLoginDate(DateUtils.getNowDate());
        sysUser.setUpdateBy(userId);
        DataPermissionHelper.ignore(() -> sysUserMapper.updateById(sysUser));
    }

    @Override
    public void checkLogin(LoginType loginType, String username, Supplier<Boolean> supplier) {
        String errorKey = GlobalConstants.PWD_ERR_CNT_KEY + username;
        String loginFail = Constants.LOGIN_FAIL;

        // 获取用户登录错误次数，默认为0 (可自定义限制策略 例如: key + username + ip)
        int errorNumber = ObjectUtil.defaultIfNull(RedisUtils.getCacheObject(errorKey), 0);
        // 锁定时间内登录 则踢出
        if (errorNumber >= maxRetryCount) {
            recordLoginInfo(username, loginFail, MessageUtils.message(loginType.getRetryLimitExceed(), maxRetryCount, lockTime));
            throw new UserException(loginType.getRetryLimitExceed(), maxRetryCount, lockTime);
        }

        if (supplier.get()) {
            // 错误次数递增
            errorNumber++;
            RedisUtils.setCacheObject(errorKey, errorNumber, Duration.ofMinutes(lockTime));
            // 达到规定错误次数 则锁定登录
            if (errorNumber >= maxRetryCount) {
                recordLoginInfo(username, loginFail, MessageUtils.message(loginType.getRetryLimitExceed(), maxRetryCount, lockTime));
                throw new UserException(loginType.getRetryLimitExceed(), maxRetryCount, lockTime);
            } else {
                // 未达到规定错误次数
                recordLoginInfo(username, loginFail, MessageUtils.message(loginType.getRetryLimitCount(), errorNumber));
                throw new UserException(loginType.getRetryLimitCount(), errorNumber);
            }
        }

        // 登录成功 清空错误次数
        RedisUtils.deleteObject(errorKey);
    }
}
